package com.ruoyi.hl.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.hl.reqbean.AddBanZuZhangBean;
import com.ruoyi.hl.reqbean.SheBeiIdListBean;
import com.ruoyi.hl.reqbean.ShouHuanListBean;
import com.ruoyi.hl.resultbean.*;
import com.ruoyi.hl.service.ShouHuanService;
import com.ruoyi.utils.HttpClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "手环相关接口")
@RestController
@RequestMapping("/shouhuan")
public class ShouHuanController extends BaseController {

    @Autowired
    private ShouHuanService shouHuanService;

    @ApiOperation(value = "请求token")
    @GetMapping("/gettoken")
    @ResponseBody
    public String getToken() {
        String result = "";
        String url = "http://47.92.252.3:18001/tsp/auth/token";
        String appkey = "10016";
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateNowStr = sdf.format(d);
        String transid = appkey + dateNowStr + "WkCRvFdYxyLy";
        String secret = "5c06516775d469481f156b7b0708dacb";
        String sign = DigestUtils.sha1Hex(secret + appkey + transid + secret);
        Map<String, String> map = new HashMap<>();
        map.put("transid", transid);
        map.put("appkey", appkey);
        map.put("sign", sign);
        result = HttpClient.doGet(url, map, null);
        TokenBean tokenBean = JSONObject.parseObject(result, TokenBean.class); //json字符串直接转给java对象
        return tokenBean.getData().getToken();
    }

    @ApiOperation(value = "获取手环设备列表（分页）") // 接口文档显示内容
    @GetMapping("/getSheBeiList")
    @ResponseBody
    public TableDataInfo getSheBeiList(ShouHuanListBean shouHuanListBean) {
        String token = getToken();
        String result = "";
        String url = "http://47.92.252.3:18001/tsp/devices/get";
        String appkey = "10016";
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateNowStr = sdf.format(d);
        String transid = appkey + dateNowStr + "WkCRvFdYxyLa";
        Map<String, String> map = new HashMap<>();
        map.put("page", shouHuanListBean.getPage());
        map.put("limit", shouHuanListBean.getLimit());

        if (!StringUtils.isEmpty(shouHuanListBean.getIsOnLine())) {
            map.put("is_online", shouHuanListBean.getIsOnLine());
        }
        if (!StringUtils.isEmpty(shouHuanListBean.getUserName())) {
            //查询设备编码根据姓名
            List<String> list = shouHuanService.selectEquipmentByName(shouHuanListBean.getUserName());
            if (null != list && list.size() > 0) {
                map.put("imei_sn", list.get(0));
            }
        }
        Map<String, String> headers = new HashMap<>();
        headers.put("transid", transid);
        headers.put("token", token);
        result = HttpClient.doGet(url, map, headers);
        SheBeiListBean sheBeiListBean = JSONObject.parseObject(result, SheBeiListBean.class); //json字符串直接转给java对象
        List<SheBeiListBean.DataBean.ResultBean> list = sheBeiListBean.getData().getResult();
        return getDataTable(list);
    }

    @ApiOperation(value = "获取手环设备列表（所有）") // 接口文档显示内容
    @GetMapping("/getAllSheBeiList")
    @ResponseBody
    public AjaxResult getAllSheBeiList() {
        List<SheBeiListBean.DataBean.ResultBean> list = new ArrayList<>();
        String token = getToken();
        String result = "";
        String result2 = "";
        String url = "http://47.92.252.3:18001/tsp/devices/get";
        String appkey = "10016";
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateNowStr = sdf.format(d);
        String transid1 = appkey + dateNowStr + "WkCRvFdYxyLb";
        String transid2 = appkey + dateNowStr + "WkCRvFdYxyLc";
        Map<String, String> map = new HashMap<>();
        map.put("page", "1");
        map.put("limit", "100");
        Map<String, String> headers = new HashMap<>();
        headers.put("transid", transid1);
        headers.put("token", token);
        result = HttpClient.doGet(url, map, headers);
        SheBeiListBean sheBeiListBean = JSONObject.parseObject(result, SheBeiListBean.class); //json字符串直接转给java对象
        if (sheBeiListBean != null && sheBeiListBean.getData() != null && sheBeiListBean.getData().getResult() != null) {
            list = sheBeiListBean.getData().getResult();
        }
        if (list.size() == 100) {
            List<SheBeiListBean.DataBean.ResultBean> list2 = new ArrayList<>();
            Map<String, String> map2 = new HashMap<>();
            map2.put("page", "2");
            map2.put("limit", "100");
            Map<String, String> headers2 = new HashMap<>();
            headers2.put("transid", transid2);
            headers2.put("token", token);
            result2 = HttpClient.doGet(url, map2, headers2);
            SheBeiListBean sheBeiListBean2 = JSONObject.parseObject(result2, SheBeiListBean.class); //json字符串直接转给java对象
            if (sheBeiListBean2 != null && sheBeiListBean2.getData() != null && sheBeiListBean2.getData().getResult() != null) {
                list2 = sheBeiListBean2.getData().getResult();
            }
            list.addAll(list2);
        }
        return AjaxResult.success(list);
    }

    @ApiOperation(value = "新增班组长-设备ID列表") // 接口文档显示内容
    @GetMapping("/getSBList")
    @ResponseBody
    public AjaxResult getSBList() {
        List<SheBeiListBean.DataBean.ResultBean> list = new ArrayList<>();
        String token = getToken();
        String result = "";
        String result2 = "";
        String url = "http://47.92.252.3:18001/tsp/devices/get";
        String appkey = "10016";
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateNowStr = sdf.format(d);
        String transid1 = appkey + dateNowStr + "WkCRvFdYxyLb";
        String transid2 = appkey + dateNowStr + "WkCRvFdYxyLc";
        Map<String, String> map = new HashMap<>();
        map.put("page", "1");
        map.put("limit", "100");
        Map<String, String> headers = new HashMap<>();
        headers.put("transid", transid1);
        headers.put("token", token);
        result = HttpClient.doGet(url, map, headers);
        SheBeiListBean sheBeiListBean = JSONObject.parseObject(result, SheBeiListBean.class); //json字符串直接转给java对象
        if (sheBeiListBean != null && sheBeiListBean.getData() != null && sheBeiListBean.getData().getResult() != null) {
            list = sheBeiListBean.getData().getResult();
        }
        if (list.size() == 100) {
            List<SheBeiListBean.DataBean.ResultBean> list2 = new ArrayList<>();
            Map<String, String> map2 = new HashMap<>();
            map2.put("page", "2");
            map2.put("limit", "100");
            Map<String, String> headers2 = new HashMap<>();
            headers2.put("transid", transid2);
            headers2.put("token", token);
            result2 = HttpClient.doGet(url, map2, headers2);
            SheBeiListBean sheBeiListBean2 = JSONObject.parseObject(result2, SheBeiListBean.class); //json字符串直接转给java对象
            if (sheBeiListBean2 != null && sheBeiListBean2.getData() != null && sheBeiListBean2.getData().getResult() != null) {
                list2 = sheBeiListBean2.getData().getResult();
            }
            list.addAll(list2);
        }
        //把ID和名称挑出来
        List<SheBeiIdListBean> resultList = new ArrayList<>();
        for (SheBeiListBean.DataBean.ResultBean item : list){
            SheBeiIdListBean bean = new SheBeiIdListBean();
            bean.setValue(item.getImei_sn());
            bean.setLabel(item.getTruename());
            resultList.add(bean);
        }
        //把已经有了的设备，从列表中拿出
        List<AddBanZuZhangBean> allBanZuList = selectBanZhuList(new AddBanZuZhangBean());
        List<SheBeiIdListBean> result1 = resultList.stream()
                .filter(item -> !allBanZuList.stream().map(e -> e.getEquipmentId()).collect(Collectors.toList()).contains(item.getValue()))
                .collect(Collectors.toList());
        return AjaxResult.success(result1);
    }

    /**
     * 查询所有班组长列表数据  不分页
     */
    public List<AddBanZuZhangBean> selectBanZhuList(AddBanZuZhangBean addBanZuZhangBean) {
        return shouHuanService.selectBanZuInfo(addBanZuZhangBean);
    }


    @ApiOperation(value = "绑定设备") // 接口文档显示内容
    @GetMapping("/bangdingshebei")
    @ResponseBody
    public AjaxResult bangDingSheBei(String imei_sn, String truename) {
        String token = getToken();
        String result = "";
        String url = "http://47.92.252.3:18001/tsp/device/bind";
        String appkey = "10016";
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateNowStr = sdf.format(d);
        String transid = appkey + dateNowStr + "WkCRvFdYxyLd";
        Map<String, String> map = new HashMap<>();
        map.put("imei_sn", imei_sn);
        map.put("truename", truename);
        map.put("mobile", "");
        map.put("uuid", imei_sn + dateNowStr);
        Map<String, String> headers = new HashMap<>();
        headers.put("transid", transid);
        headers.put("token", token);
        result = HttpClient.doGet(url, map, headers);
        SheBeiListBean sheBeiListBean = JSONObject.parseObject(result, SheBeiListBean.class); //json字符串直接转给java对象
        return AjaxResult.success(sheBeiListBean);
    }

    @ApiOperation(value = "修改设备对应用户名称") // 接口文档显示内容
    @GetMapping("/update")
    @ResponseBody
    public AjaxResult unBangDingSheBei(String imei_sn, String truename) {
        String token = getToken();
        String result = "";
        String url = "http://47.92.252.3:18001/tsp/device/update";
        String appkey = "10016";
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateNowStr = sdf.format(d);
        String transid = appkey + dateNowStr + "WkCRvFdYxyLe";
        Map<String, String> map = new HashMap<>();
        map.put("imei_sn", imei_sn);
        map.put("truename", truename);
        Map<String, String> headers = new HashMap<>();
        headers.put("transid", transid);
        headers.put("token", token);
        try {
            result = HttpClient.doPut(url, headers, map, "");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return AjaxResult.success();
    }

    @ApiOperation(value = "设置血压上报时间间隔") // 接口文档显示内容
    @GetMapping("/booldUpdate")
    @ResponseBody
    public AjaxResult booldUpdate(String imei_sn, String second) {
        String token = getToken();
        String result = "";
        String url = "http://47.92.252.3:18001/tsp/blood/upload/set";
        String appkey = "10016";
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateNowStr = sdf.format(d);
        String transid = appkey + dateNowStr + "WkCRvFdYxyLf";
        Map<String, String> map = new HashMap<>();
        map.put("imei_sn", imei_sn);
        map.put("second", second);
        Map<String, String> headers = new HashMap<>();
        headers.put("transid", transid);
        headers.put("token", token);
        try {
            result = HttpClient.doPut(url, headers, map, "");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return AjaxResult.success();
    }

    @ApiOperation(value = "设置心率上报时间间隔") // 接口文档显示内容
    @GetMapping("/heartUpdate")
    @ResponseBody
    public AjaxResult heartUpdate(String imei_sn, String second) {
        String token = getToken();
        String result = "";
        String url = "http://47.92.252.3:18001/tsp/heart/upload/set";
        String appkey = "10016";
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateNowStr = sdf.format(d);
        String transid = appkey + dateNowStr + "WkCRvFdYxyLg";
        Map<String, String> map = new HashMap<>();
        map.put("imei_sn", imei_sn);
        map.put("second", second);
        Map<String, String> headers = new HashMap<>();
        headers.put("transid", transid);
        headers.put("token", token);
        try {
            result = HttpClient.doPut(url, headers, map, "");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return AjaxResult.success();
    }


    @ApiOperation(value = "设置体温上报时间间隔") // 接口文档显示内容
    @GetMapping("/temperatureUpdate")
    @ResponseBody
    public AjaxResult temperatureUpdate(String imei_sn, String second) {
        String token = getToken();
        String result = "";
        String url = "http://47.92.252.3:18001/tsp/temperature/upload/set";
        String appkey = "10016";
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateNowStr = sdf.format(d);
        String transid = appkey + dateNowStr + "WkCRvFdYxyLh";
        Map<String, String> map = new HashMap<>();
        map.put("imei_sn", imei_sn);
        map.put("second", second);
        Map<String, String> headers = new HashMap<>();
        headers.put("transid", transid);
        headers.put("token", token);
        try {
            result = HttpClient.doPut(url, headers, map, "");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return AjaxResult.success();
    }

    @ApiOperation(value = "获取设备详情") // 接口文档显示内容
    @GetMapping("/shebeiDetail")
    @ResponseBody
    public AjaxResult shebeiDetail(String imei_sn, String uuid) {
        String token = getToken();
        String result1 = "";
        String result2 = "";
        String result3 = "";
        String url1 = "http://47.92.252.3:18001/tsp/heart/get";//最后一次心率数据
        String url2 = "http://47.92.252.3:18001/tsp/blood/get";//最后一次血压数据
        String url3 = "http://47.92.252.3:18001/tsp/temperature/get";//最后一次体温数据
        String appkey = "10016";
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateNowStr = sdf.format(d);
        String transid1 = appkey + dateNowStr + "WkCRvFdYxyLi";
        String transid2 = appkey + dateNowStr + "WkCRvFdYxyLj";
        String transid3 = appkey + dateNowStr + "WkCRvFdYxyLk";
        Map<String, String> map = new HashMap<>();
        map.put("imei_sn", imei_sn);
        map.put("uuid", uuid);
        Map<String, String> headers1 = new HashMap<>();
        headers1.put("transid", transid1);
        headers1.put("token", token);
        Map<String, String> headers2 = new HashMap<>();
        headers2.put("transid", transid2);
        headers2.put("token", token);
        Map<String, String> headers3 = new HashMap<>();
        headers3.put("transid", transid3);
        headers3.put("token", token);
        result1 = HttpClient.doGet(url1, map, headers1);
        result2 = HttpClient.doGet(url2, map, headers2);
        result3 = HttpClient.doGet(url3, map, headers3);
        SheBeiDetailBean detailBean = new SheBeiDetailBean();
        XinLvBean xinLvBean = JSONObject.parseObject(result1, XinLvBean.class);
        if (!StringUtils.isEmpty(result1) && xinLvBean.getStatus() == 0 && xinLvBean.getData() != null) {
            detailBean.setHeart_rate(xinLvBean.getData().getHeart_rate() + "");
            detailBean.setHeart_time(xinLvBean.getData().getCreated() + "");
        }
        XueYaBean xueYaBean = JSONObject.parseObject(result2, XueYaBean.class);
        if (!StringUtils.isEmpty(result2) && xueYaBean.getStatus() == 0 && xueYaBean.getData() != null) {
            detailBean.setMax_rate(xueYaBean.getData().getMax_rate() + "");
            detailBean.setMin_rate(xueYaBean.getData().getMin_rate() + "");
            detailBean.setBlood_time(xueYaBean.getData().getCreated() + "");
        }
        TiWenBean tiWenBean = JSONObject.parseObject(result3, TiWenBean.class);
        if (!StringUtils.isEmpty(result3) && tiWenBean.getStatus() == 0 && tiWenBean.getData() != null) {
            detailBean.setTemperature(tiWenBean.getData().getTemperature() + "");
            detailBean.setTemperature_time(tiWenBean.getData().getCreated() + "");
        }
        return AjaxResult.success(detailBean);
    }

    @ApiOperation(value = "获取心率历史数据") // 接口文档显示内容
    @GetMapping("/gethearthistory")
    @ResponseBody
    public TableDataInfo getHeartHistory(String imei_sn, String page, String limit) {
        String token = getToken();
        String result1 = "";
        String url1 = "http://47.92.252.3:18001/tsp/hearts/get";//最后一次心率数据
        String appkey = "10016";
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateNowStr = sdf.format(d);
        String transid1 = appkey + dateNowStr + "WkCRvFdYxyLl";

        Map<String, String> map = new HashMap<>();
        map.put("imei_sn", imei_sn);
        map.put("start_time", getBeforeDayTime(-1));
        map.put("end_time", getBeforeDayTime(0));
        map.put("page", page);
        map.put("limit", limit);
        Map<String, String> headers1 = new HashMap<>();
        headers1.put("transid", transid1);
        headers1.put("token", token);
        result1 = HttpClient.doGet(url1, map, headers1);
        XinLvHistoryBean xinLvBean = JSONObject.parseObject(result1, XinLvHistoryBean.class);
        if (xinLvBean != null && xinLvBean.getData() != null && xinLvBean.getData().getResult() != null) {
            return getDataTable(xinLvBean.getData().getResult());
        }
        return getDataTable(new ArrayList<>());
    }

    @ApiOperation(value = "获取血压历史数据") // 接口文档显示内容
    @GetMapping("/getbloodhistory")
    @ResponseBody
    public TableDataInfo getBloodHistory(String imei_sn, String page, String limit) {
        String token = getToken();
        String result1 = "";
        String url1 = "http://47.92.252.3:18001/tsp/bloods/get";//最后一次心率数据
        String appkey = "10016";
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateNowStr = sdf.format(d);
        String transid1 = appkey + dateNowStr + "WkCRvFdYxyLm";

        Map<String, String> map = new HashMap<>();
        map.put("imei_sn", imei_sn);
        map.put("start_time", getBeforeDayTime(-1));
        map.put("end_time", getBeforeDayTime(0));
        map.put("page", page);
        map.put("limit", limit);
        Map<String, String> headers1 = new HashMap<>();
        headers1.put("transid", transid1);
        headers1.put("token", token);
        result1 = HttpClient.doGet(url1, map, headers1);
        XueYaHistoryBean xueYaHistoryBean = JSONObject.parseObject(result1, XueYaHistoryBean.class);
        if (xueYaHistoryBean != null && xueYaHistoryBean.getData() != null && xueYaHistoryBean.getData().getResult() != null) {
            return getDataTable(xueYaHistoryBean.getData().getResult());
        }
        return getDataTable(new ArrayList<>());
    }

    @ApiOperation(value = "获取体温历史数据") // 接口文档显示内容
    @GetMapping("/gettiwenhistory")
    @ResponseBody
    public TableDataInfo getTiWenHistory(String imei_sn, String page, String limit) {
        String token = getToken();
        String result1 = "";
        String url1 = "http://47.92.252.3:18001/tsp/temperatures/get";//最后一次心率数据
        String appkey = "10016";
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateNowStr = sdf.format(d);
        String transid1 = appkey + dateNowStr + "WkCRvFdYxyLn";

        Map<String, String> map = new HashMap<>();
        map.put("imei_sn", imei_sn);
        map.put("start_time", getBeforeDayTime(-1));
        map.put("end_time", getBeforeDayTime(0));
        map.put("page", page);
        map.put("limit", limit);
        Map<String, String> headers1 = new HashMap<>();
        headers1.put("transid", transid1);
        headers1.put("token", token);
        result1 = HttpClient.doGet(url1, map, headers1);
        TiWenHistoryBean tiWenHistoryBean = JSONObject.parseObject(result1, TiWenHistoryBean.class);
        if (tiWenHistoryBean != null && tiWenHistoryBean.getData() != null && tiWenHistoryBean.getData().getResult() != null) {
            return getDataTable(tiWenHistoryBean.getData().getResult());
        }
        return getDataTable(new ArrayList<>());
    }

    /**
     * 前一天时间
     */
    private String getBeforeDayTime(int i) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, i);
        date = calendar.getTime();
        return sdf.format(date);
    }


//    @ApiOperation(value = "通过数据库获取设备详情") // 接口文档显示内容
//    @GetMapping("/shebeiDetails")
//    @ResponseBody
//    public AjaxResult shebeiDetail(String imei_sn) {
//
//        SheBeiDetailBean detailBean = new SheBeiDetailBean();
//        if (!StringUtils.isEmpty(result1)){
//            XinLvBean xinLvBean = JSONObject.parseObject(result1, XinLvBean.class);
//            detailBean.setHeart_rate(xinLvBean.getData().getHeart_rate()+"");
//            detailBean.setHeart_time(xinLvBean.getData().getCreated()+"");
//        }
//        if (!StringUtils.isEmpty(result2)){
//            XueYaBean xueYaBean = JSONObject.parseObject(result2, XueYaBean.class);
//            detailBean.setMax_rate(xueYaBean.getData().getMax_rate()+"");
//            detailBean.setMin_rate(xueYaBean.getData().getMin_rate()+"");
//            detailBean.setBlood_time(xueYaBean.getData().getCreated()+"");
//        }
//        if (!StringUtils.isEmpty(result3)){
//            TiWenBean tiWenBean = JSONObject.parseObject(result3, TiWenBean.class);
//            detailBean.setTemperature(tiWenBean.getData().getTemperature()+"");
//            detailBean.setTemperature_time(tiWenBean.getData().getCreated()+"");
//        }
//        return AjaxResult.success(detailBean);
//    }
}
